#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>

#define N 32

int socks[N];

void close_sock(int sockfd, int i) {
    close(socks[i]);
    socks[i] = 0;
    printf("client %d exited.\n", sockfd);
}

void talk_to_client(int sockfd, int i) {
    int len;
    char buffer[N];

    errno = 0;
    len = read(sockfd, buffer, N);
    if (len == 0 && errno == 0) {
        close_sock(sockfd, i);
        return;
    }

    if (len < 0) {
        if (errno == EAGAIN) {
            return;
        }

        if (errno == ECONNRESET || errno == ECONNABORTED || errno == ECONNREFUSED) {
            close_sock(sockfd, i);
            return;
        }
        else
            printf("%d\n", errno);
    }
    else { 
        write(sockfd, buffer, len);
    }
}

int main(){
    int serv_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    struct sockaddr_in serv_addr;
    char buffer[N];
    int len, i;

    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    serv_addr.sin_port = htons(54321);

    bind(serv_sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr));

    listen(serv_sock, 20);
    struct sockaddr_in clnt_addr;
    socklen_t clnt_addr_size = sizeof(clnt_addr);
    printf("server is listening...\n");
    int flags = fcntl(serv_sock, F_GETFL, 0);
    fcntl(serv_sock, F_SETFL, flags|O_NONBLOCK);
    int index = 0;
    while (1) {
        errno = 0;
        int clnt_sock = accept(serv_sock, (struct sockaddr*)&clnt_addr, &clnt_addr_size);
        if (clnt_sock < 0 && errno == 11) {
            ; // do nothing
        }
        else {
            flags = fcntl(clnt_sock, F_GETFL, 0);
            fcntl(clnt_sock, F_SETFL, flags|O_NONBLOCK);
            socks[index++] = clnt_sock;
        }

        for (i = 0; i < N; i++) {
            if (socks[i]) {
                talk_to_client(socks[i], i);
            }
        }
    }

    close(serv_sock);
    return 0;
}

